package artaza.controlador;

import artaza.persistencia.*;
import artaza.service.UsuarioService;
import java.util.Collection;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

@Controller
@SessionAttributes("usuario")
public class UsuarioController {

    private UsuarioService usuarioService;
    private AuthenticationManager authenticationManager;

    @Autowired
    @Required
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Autowired
    @Required
    public void setUsuarioService(UsuarioService usuarioService) {
        this.usuarioService = usuarioService;
    }

    @RequestMapping(method = RequestMethod.GET, value = "/getUsuarioConectado", headers = "Accept=application/json")
    public
    @ResponseBody
    Usuario getUser() {
        return usuarioService.getCurrentUser();
    }

    @RequestMapping(method = RequestMethod.GET, value = "/getLoginURL")
    public String getLoginURL() {
        return "/login";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password, Model model) {

        try {
            //System.out.println("AQUI 1 UserController login ");
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            //System.out.println("AQUI 2 UserController login ");
            UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password);
            //System.out.println("AQUI 3 UserController login ");
            authToken.setDetails(authentication.getDetails());
            //System.out.println("AQUI 4 UserController login authenticationManager="+authenticationManager);
            Authentication newAuth = authenticationManager.authenticate(authToken);
            //System.out.println("AQUI 5 UserController login ");
            SecurityContextHolder.getContext().setAuthentication(newAuth);
            //System.out.println("AQUI 6 UserController login ");
            if (newAuth.isAuthenticated()) {
                model.addAttribute("usuario", usuarioService.getCurrentUser());
                //rdo = "Estás conectado como" + username;
            } else {
            }
            //System.out.println("AQUI 7 UserController login ");

        } catch (Exception unfe) {
            String rdo = " ERROR " + unfe.getMessage();
            unfe.printStackTrace();
            model.addAttribute("error_log", "Error al conectar. Comprueba usuario y contraseña");
            return "redirect:falloautenticacion";
        }
        return "redirect:ir_portada";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/logout")
    public String logout(HttpSession sesion, SessionStatus sessionStatus, @ModelAttribute("usuario") Usuario usuario) throws java.io.IOException {
        System.out.println("UsuarioController logout se está desconectando " + usuario.getUsername());
        SecurityContextHolder.getContext().setAuthentication(null);
        Usuario u = (Usuario) sesion.getAttribute("usuario");
        System.out.println("UsuarioController logout se está desconectando2 " + usuario.getUsername());
        sessionStatus.setComplete();
        //Otra forma: sesion.invalidate();
        return "/portada";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/ir_registro")
    public String IrRegistro() {
        return "/registro";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/ir_portada")
    public String IrPortada() {
        return "/portada";
    }

    @RequestMapping(method = RequestMethod.POST, value = "/nuevo_usuario")
    public String NuevoUsuario(@RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("nombre") String nombre,
            @RequestParam("apellidos") String apellidos,
            @RequestParam("dni") String dni,
            @RequestParam("telefono") String telefono,
            @RequestParam("correo") String correo,
            Model model) {
       

        try {
            Usuario buscado = usuarioService.buscarUsername(username);
            return "redirect:/registro";
        } catch (Exception e) {

            Usuario usuario = new Usuario(username, password, nombre, apellidos, dni, telefono, correo);
            usuarioService.crearUsuario(usuario);
            return login(username, password, model);

        }
    }

    @RequestMapping(value = "/listadousers", method = RequestMethod.GET)
    public String doShowUsuarios(Model model) {

        final Collection<Usuario> usuarios = usuarioService.getAllusuarios();
        model.addAttribute("usuarios", usuarios);
        final Collection<Rol> roles = usuarioService.getAllRoles();
        model.addAttribute("roles", roles);


        return "/listadousers";
    }

    @RequestMapping(value = "/asignar_admin", method = RequestMethod.POST)
    public String asignarAdministrador(@RequestParam("username") String username, Model model) {

        Usuario u = usuarioService.buscarUsername(username);
        // if(!usuarioService.isAdmin() ){
        usuarioService.crearAdmin(u);

        return "redirect:listadousers";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/adminSecured/ir_index")
    public String IrAAdministracion() {
        return "/index";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/ir_a_crearmensaje")
    public String IrAMensaje() {
        return "/crearmensaje";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/accesoDenegado")
    public String IrAAccesodenegado() {
        return "redirect:/accessDenied.html";
    }

    @RequestMapping(method = RequestMethod.GET, value = "/falloautenticacion")
    public String IrAFalloAutenticacion() {
        return "redirect:/falloautenticacion.html";
    }
}
